package jp.bgbt.fles.app.bluetooth;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothProfile;

import com.common.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;

import jp.bgbt.fles.app.bean.EventMsg;
import jp.bgbt.fles.app.bean.StrategyDetailsBean;
//import jp.bgbt.fles.app.utils.BeautyCountdownUtil;

public class BleConnectCallBack extends BluetoothGattCallback {

    private String TAG = getClass().getSimpleName();

    private OnBleConnectListener listener;

    public BleConnectCallBack(OnBleConnectListener listener) {
        this.listener = listener;
    }

    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        LogUtil.e("蓝牙状态变化： status = " + status + "  ---   newState = " + newState);
        if (status == 133) {
            LogUtil.e("******     ble disabled   ************");
            BleDeviceInfo.getInstance().setDeviceConnected(false);
            EventBus.getDefault().post(new EventMsg(EventMsg.BLE_133));
            return;
        }
        if ((status != BluetoothProfile.STATE_CONNECTED)
                && (status != BluetoothProfile.STATE_DISCONNECTED)
                && newState != BluetoothProfile.STATE_DISCONNECTED) {
            //非主动断开，默认自动重连
            LogUtil.d("被动断开，开始自动重连");
            BleDeviceInfo.getInstance().setDeviceConnected(false);
            return;
        }
        if (newState == BluetoothProfile.STATE_CONNECTED) {// 当蓝牙设备已经连接
            LogUtil.d("设备已连接");
            if (listener != null)
                listener.onConnected(gatt.getDevice().getAddress());
            return;
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { //设备断开连接
            LogUtil.d("设备已断开");
            if (listener != null)
                listener.onDisConnected();
            BleDeviceInfo.getInstance().setDeviceConnected(false);
            EventBus.getDefault().post(new EventMsg(EventMsg.MSG_BLE_DISCONNECTED));
//            BeautyCountdownUtil.getInstance().stopCountDown();
        }
        BleDeviceInfo.getInstance().setDeviceConnected(false);
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        LogUtil.e("onServicesDiscovered  " + status);
        if (status == BluetoothGatt.GATT_SUCCESS) {// 发现可用蓝牙服务
            LogUtil.d("发现可用服务");
            if (listener != null)
                listener.onBleServiceDiscovered();
            EventBus.getDefault().post(new EventMsg(EventMsg.MSG_BLE_CONNECTED));
        } else {
            LogUtil.d("蓝牙服务不可用 " + status);
            BleDeviceInfo.getInstance().setDeviceConnected(false);
        }
    }


    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        String uuid = characteristic.getUuid().toString().trim();
        final byte[] data = characteristic.getValue();
        if (BleConstant.CHA_UUID1.equals(uuid)) {
            StringBuffer bf = new StringBuffer();
            for (int i = 0; i < data.length; i++) {
                bf.append(String.format("%02X", data[i]).toString().trim());
            }
            String dataValues = bf.toString();
//            LogUtil.e("主机响应  " + dataValues);

            /** 获取到随机码 */
            if (dataValues.contains("EB0C")) {
                setRandomData(dataValues);
                return;
            }
            /** 读硬件版本信息 */
            if (dataValues.contains("EB0801")) {
                String version = String.format("%02X", data[3]).toString().trim();
                BleDeviceInfo.getInstance().setDeviceVersion(version);
                BleCommandUtil.getInstance().setCommandResponseReceived2(data);
                EventBus.getDefault().post(new EventMsg(EventMsg.MSG_DEVICE_VERSION));
                return;
            }
            /** 读取驱动总时长成功 */
            if (dataValues.contains("EB0702")) {
                BleCommandUtil.getInstance().setCommandResponseReceived2(data);
                String low = String.format("%02X", data[3]).trim();
                String hight = String.format("%02X", data[4]).trim();
                int runtime = (int) (Integer.parseInt(hight + low, 16) * 1f / 10 * 60);
                LogUtil.e("已驱动总时长：" + runtime + "分钟");
//                BleDeviceInfo.getInstance().setUsedTime(runtime);
                EventBus.getDefault().post(new EventMsg(EventMsg.MSG_TOTAL_RUNTIME, runtime));
                return;
            }
            /** 暂停美肤 */
            if (dataValues.contains("EA07")) {
                BleCommandUtil.getInstance().setCommandResponseReceived1(data);
                pauseBeautySkin();
                return;
            }
            /** 继续美肤  (EC0800AE为红外，可省略)*/
            if (dataValues.contains("EA08") || dataValues.contains("EC0800AE")) {
                BleCommandUtil.getInstance().setCommandResponseReceived1(data);
                continueBeautySkin();
                return;
            }
            /** 打开wifi成功 */
            if (dataValues.contains("7FD6")) {
                BleCommandUtil.getInstance().setCommandResponseReceived2(data);
                EventBus.getDefault().post(new EventMsg(EventMsg.MSG_OPEN_WIFI_SUCCESS));
                return;
            }
            /** 读到wifi的mac地址 */
            if (dataValues.contains("EBD806")) {
                BleCommandUtil.getInstance().setCommandResponseReceived2(data);
                String wifiAddr = dataValues.substring(6, 18);
                BleDeviceInfo.getInstance().setWifiAddr(wifiAddr);
                EventBus.getDefault().post(new EventMsg(EventMsg.MSG_WIFI_ADDR_RECEIVED));
                LogUtil.e("wifi 地址为  " + wifiAddr);
                return;
            }
            /** APP结束美肤成功 */
            if (dataValues.contains("7F80")) {
                BleCommandUtil.getInstance().setCommandResponseReceived1(data);
                BleDeviceInfo.getInstance().setNurseState(BleConstant.NURSE_INIT);
                EventBus.getDefault().post(new EventMsg(EventMsg.NURSE_STATE_CHANGED));
                BleCommandUtil.getInstance().sendCommand(BleConstant.readUsedTime);
                return;
            }
            /** 收到硬件自动结束美肤的指令 */
            if (dataValues.contains("EC8000AE")) {
                BleDeviceInfo.getInstance().setNurseState(BleConstant.NURSE_INIT);
                EventBus.getDefault().post(new EventMsg(EventMsg.NURSE_STATE_CHANGED, true));
                BleCommandUtil.getInstance().sendCommand(BleConstant.readUsedTime);
                return;
            }
            /** 响应 */
            if (dataValues.startsWith("7F")) {
                BleCommandUtil.getInstance().setCommandResponseReceived2(data);
                /** 开启美肤成功 */
                if (dataValues.contains("7F1C")) {
                    int ledPattern = StrategyDetailsBean.getInstance().getLedPattern();
                    int remainTime = ledPattern == 0 ? 20 : 10;
                    //设置倒计时60秒
//                    BeautyCountdownUtil.getInstance().setRemainTime(remainTime * 60);
                    EventBus.getDefault().post(new EventMsg(EventMsg.MSG_BEAUTY_RUN_SUCCESS));
                    return;
                }
                return;
            }
            /** 美肤剩余时间校正 */
            if (dataValues.contains("EA031D")) {
                int time = Integer.valueOf(String.format("%02X ", data[5]).toString().trim()
                        + String.format("%02X ", data[4]).toString().trim(), 16);
                int timeok = time / 10;
                LogUtil.d("剩余时间 " + timeok);
//                BeautyCountdownUtil.getInstance().setRemainTime(timeok);
                return;
            }
            /** 获取到电压 */
            if (dataValues.contains("EB5602")) {
                BleCommandUtil.getInstance().setCommandResponseReceived2(data);
                String data3 = String.format("%02X ", data[3]).trim();
                String data4 = String.format("%02X ", data[4]).trim();
                int dianya = Integer.parseInt(data3 + data4, 16);
                LogUtil.d("当前电压 " + dianya);
                BleDeviceInfo.getInstance().setRemainEle(dianya);
                EventBus.getDefault().post(new EventMsg(EventMsg.MSG_GET_ELE_PRESSURE));
                return;
            }
        }
    }

    private void pauseBeautySkin() {
        if (BleDeviceInfo.getInstance().getNurseState() != BleConstant.NURSE_PAUSED) {
            BleDeviceInfo.getInstance().setNurseState(BleConstant.NURSE_PAUSED);
            EventBus.getDefault().post(new EventMsg(EventMsg.NURSE_STATE_CHANGED));
        }
    }

    private void continueBeautySkin() {
        if (BleDeviceInfo.getInstance().getNurseState() != BleConstant.NURSE_RUNNING) {
            BleDeviceInfo.getInstance().setNurseState(BleConstant.NURSE_RUNNING);
            EventBus.getDefault().post(new EventMsg(EventMsg.NURSE_STATE_CHANGED));
        }
    }

    private void setRandomData(String dataValues) {
        int indexI = dataValues.indexOf("EB0C");
        StringBuffer buffer = new StringBuffer();
        buffer.append(dataValues.substring(indexI, indexI + 24));
        /** 初始化开关状态 */
        int nurseType = Integer.valueOf(
                dataValues.substring(indexI + 20, indexI + 22),
                16).intValue(); // 当前的服务类型
        int runState = Integer.valueOf(
                dataValues.substring(indexI + 22, indexI + 24),
                16).intValue(); // 当前设备是暂停还是继续状态
        BleDeviceInfo.getInstance().setNurseType(nurseType);
        BleDeviceInfo.getInstance().setNurseState(runState);
        // 剩余时间
        int time = Integer.valueOf(dataValues.substring(indexI + 26, indexI + 30),
                16).intValue();
        int timeok = time / 10;
        String random = buffer.toString().substring(0, 24);
        LogUtil.e("随机码为:" + random + " nurseType = " +
                nurseType + " --- nurseState = " + runState + " --- time " + timeok);
        BleDeviceInfo.getInstance().setDeviceRandom(random);
        EventBus.getDefault().post(new EventMsg(EventMsg.MSG_RANDOM_RECEIVED, timeok));
    }


    public interface OnBleConnectListener {

        void onConnected(String mac);

        void onBleServiceDiscovered();

        void onDisConnected();
    }
}